package 用队列实现栈;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

public class MyStack {

    private Queue<Integer> queue1;
    private Queue<Integer> queue2;

    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    // 入栈
    public void push(int x) {
        if (queue1.isEmpty() && queue2.isEmpty()) {
            queue1.offer(x);
        } else if (!queue1.isEmpty()) {
            queue1.offer(x);
        } else {
            queue2.offer(x);
        }
    }

    // 出栈
    public int pop() {
        int size1 = queue1.size() - 1;
        int size2 = queue2.size() - 1;
        if (empty()) {
            return -1;
        } else if (!queue1.isEmpty()) {
            for (int i = 0; i < size1; i++) {
                queue2.offer(queue1.poll());
            }
            return queue1.poll();
        } else {
            for (int i = 0; i < size2; i++) {
                queue1.offer(queue2.poll());
            }
            return queue2.poll();
        }
    }

    // peek一下，查看栈顶元素         错误！
/*    public int top2() {
        int size1 = queue1.size() - 1;
        int size2 = queue2.size() - 1;
        if (empty()) {
            return -1;
        } else if (!queue1.isEmpty()) {
            for (int i = 0; i < size1; i++) {
                queue2.offer(queue1.poll());
            }
            return queue1.peek();  // 没有入队
        } else {
            for (int i = 0; i < size2; i++) {
                queue1.offer(queue2.poll());
            }
            return queue2.poll();
        }
    }*/
    public int top() {
        if (empty()) {
            return -1;
        }
        if (!queue1.isEmpty()) {
            int size1 = queue1.size();
            int val = -1;
            for (int i = 0; i < size1; i++) {
                val = queue1.poll();
                queue2.offer(val);
            }
            return val;
        } else {
            int val = -1;
            int size2 = queue2.size();
            for (int i = 0; i < size2; i++) {
                val = queue2.poll();
                queue1.offer(val);
            }
            return val;
        }
    }

    // 判断栈空
    public boolean empty() {
        if (queue1.isEmpty() && queue2.isEmpty()){
            return true;
        }
        return false;
    }
}
